package laps.dataaccess.mysql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import laps.dataaccess.PublicHolidayDAO;

public class PublicHolidayDAOImpl implements PublicHolidayDAO {

	private Connection connection;

	public PublicHolidayDAOImpl(Connection connection) {
		super();
		this.connection = connection;
	}

	@Override
	public HashMap<Date, String> getPublicHolidaysBetween(Date startDate, Date endDate) {
		
		HashMap<Date, String> result = new HashMap<Date, String>();
		
		String sqlStatement = "select * from laps_db.public_holiday;";
			
		Statement statement = null;
		ResultSet resultSet = null;
		
		try {
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sqlStatement);
			
			while(resultSet.next()) {
				
				Date d = createDate(resultSet.getInt("year"),
						resultSet.getInt("month"),
						resultSet.getInt("day"));
				String desc = resultSet.getString("description");
				
				if (d.after(startDate)&&d.before(endDate))
					result.put(d,desc);
			}
			
		} catch(SQLException e) {
			e.printStackTrace();
		}
		
		
		return result;
	}
	
	private Date createDate(int year, int month, int day) {
		Date date = null;
		String yearStr = "";
		String monthStr = "";
		String dayStr = "";
		
		if(day<10) {
			dayStr = "0" + day;
		} else {
			dayStr = day + "";
		}
		
		if(month<10) {
			monthStr = "0" + month;
		} else {
			monthStr = month + "";
		}
		
		yearStr = year + "";
		
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = df.parse(yearStr+"-"+monthStr+"-"+dayStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return date;
	}
	
	
}
